import { Button, DatePicker, Form, Input, Radio, Row, Select, Spin, TimePicker } from 'antd';
import React, { useEffect, useState } from 'react';
// @ts-ignore
import { TJModel } from '@/pages/ETrade/components';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import isMoment from 'dayjs/plugin/isMoment';
import localeData from 'dayjs/plugin/localeData';
import weekday from 'dayjs/plugin/weekday';
import type { Dispatch } from 'redux';
import { connect } from 'umi';
import styles from './index.less';
import { validateNoSpaces } from '../../../helper';

const { RangePicker } = DatePicker;
const { Option } = Select;

dayjs.extend(weekday);
dayjs.extend(localeData);
dayjs.extend(customParseFormat);
dayjs.extend(isMoment);

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 18 },
  },
};

interface WindowProps {
  state: {
    windowSetVisible: boolean;
    windowName: string;
    startMarkDate: string;
    endMarkDate: string;
    reportDate: string;
    startReportTime: string;
    endReportTime: string;
  };
  onCancelWindowSetVisible: () => void;
  onFinish: (values: any) => void;
  buttonPermissions: any;
  list: any[];
  windowConfigs: any;
  configLoading: boolean;
  dispatch: Dispatch;
}

type FieldType = {
  windowName?: string;
  windowType: 'add' | 'edit';
  marketDate: [dayjs.Dayjs, dayjs.Dayjs];
  reportDate: dayjs.Dayjs;
  reportTime: [dayjs.Dayjs, dayjs.Dayjs];
};

const Window: React.FC<WindowProps> = ({
  state,
  onCancelWindowSetVisible,
  onFinish,
  windowConfigs,
  configLoading,
  buttonPermissions,
  list,
  dispatch,
}) => {
  const [windowType, setWindowType] = useState('add'); // 窗口配置--默认新增
  const [form] = Form.useForm();

  useEffect(() => {
    if (!state.windowSetVisible) {
      form.resetFields();
      setWindowType('add');
    } else {
      form.setFieldsValue(getInitialValues(state, windowType));
    }
  }, [state.windowSetVisible]);

  useEffect(() => {
    form.setFieldsValue(getInitialValues(state, windowType));
  }, [windowType]);

  useEffect(() => {
    if (windowConfigs) {
      form.setFieldsValue({
        windowName: windowConfigs.windowName,
        marketDate: [dayjs(windowConfigs?.startMarkDate), dayjs(windowConfigs?.endMarkDate)],
        reportDate: dayjs(windowConfigs?.reportDate),
        reportTime: [
          dayjs(windowConfigs?.startReportTime, 'HH:mm'),
          dayjs(windowConfigs?.endReportTime, 'HH:mm'),
        ],
      });
    }
  }, [windowConfigs]);

  const handleCancel = () => {
    form.resetFields();
    setWindowType('add');
    onCancelWindowSetVisible();
  };

  const getInitialValues = (state: WindowProps['state'], windowType: string) => {
    try {
      return {
        windowType,
        windowId: null,
        windowEdit: null,
        windowName: null,
        marketDate: null,
        reportDate: null,
        reportTime: null,
      };
    } catch (error) {
      // 如果解析失败，返回默认值
      return {
        windowType,
      };
    }
  };

  const EditWin = () => {
    return (
      <div>
        <Form.Item<FieldType>
          label="窗口名称"
          name="windowEdit"
          rules={[{ required: true, message: '窗口名称必填!' }]}
        >
          <Select
            placeholder="请选择窗口名称"
            onChange={(value: number) => {
              if (value) {
                dispatch({
                  type: 'ListingTransactionDeclaration/fetchQueryWindow',
                  payload: value,
                });
              }
            }}
          >
            {list.map((item) => {
              return (
                <Option value={item.windowId} key={item.windowId}>
                  {item.windowName}
                </Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item<FieldType>
          label="名称编辑"
          name="windowName"
          rules={[
            { required: true, message: '窗口名称必填!' },
            { validator: validateNoSpaces('窗口名称') },
          ]}
        >
          <Input placeholder="请输入窗口名称" allowClear />
        </Form.Item>

        <Form.Item<FieldType>
          label="标的范围"
          name="marketDate"
          rules={[{ required: true, message: '标的范围必填!' }]}
        >
          <RangePicker format="YYYYMMDD" />
        </Form.Item>

        <Form.Item<FieldType>
          label="交易申报时间"
          name="reportDate"
          rules={[{ required: true, message: '交易申报日期必填!' }]}
        >
          <DatePicker format="YYYYMMDD" />
        </Form.Item>
        <Form.Item<FieldType>
          label={null}
          name="reportTime"
          rules={[{ required: true, message: '交易申报时间必填!' }]}
          style={{ justifyContent: 'end' }}
        >
          <TimePicker.RangePicker format={'HH:mm'} />
        </Form.Item>
      </div>
    );
  };

  return (
    <div className={styles.molContent}>
      {state.windowSetVisible && (
        <TJModel
          width={520}
          title={'窗口设置'}
          onCancel={handleCancel}
          visible={state.windowSetVisible}
          footer={false}
        >
          <Form
            form={form}
            name="win"
            labelAlign="left"
            {...formItemLayout}
            initialValues={getInitialValues(state, windowType)}
            onFinish={onFinish}
            autoComplete="off"
          >
            <Form.Item<FieldType> name="windowType">
              <Radio.Group onChange={(e) => setWindowType(e.target.value)} value={windowType}>
                <Radio value="add"> 新增 </Radio>
                <Radio value="edit"> 编辑 </Radio>
              </Radio.Group>
            </Form.Item>
            {windowType === 'add' ? (
              <div>
                <Form.Item<FieldType>
                  label="窗口名称"
                  name="windowName"
                  rules={[
                    { required: true, message: '窗口名称必填!' },
                    { validator: validateNoSpaces('窗口名称') },
                  ]}
                >
                  <Input placeholder="请输入窗口名称" allowClear />
                </Form.Item>

                <Form.Item<FieldType>
                  label="标的范围"
                  name="marketDate"
                  rules={[{ required: true, message: '标的范围必填!' }]}
                >
                  <RangePicker format="YYYYMMDD" />
                </Form.Item>

                <Form.Item<FieldType>
                  label="交易申报时间"
                  name="reportDate"
                  rules={[{ required: true, message: '交易申报日期必填!' }]}
                >
                  <DatePicker format="YYYYMMDD" />
                </Form.Item>
                <Form.Item<FieldType>
                  label={null}
                  name="reportTime"
                  rules={[{ required: true, message: '交易申报时间必填!' }]}
                  style={{ justifyContent: 'end' }}
                >
                  <TimePicker.RangePicker format={'HH:mm'} />
                </Form.Item>
              </div>
            ) : (
              <Spin spinning={configLoading}>{EditWin()}</Spin>
            )}
            <Row style={{ marginTop: 10, justifyContent: 'end' }}>
              <div>
                <Button onClick={onCancelWindowSetVisible}>取消</Button>
                <Button type="primary" htmlType="submit">
                  确认
                </Button>
              </div>
            </Row>
          </Form>
        </TJModel>
      )}
    </div>
  );
};

export default connect(({ global, ListingTransactionDeclaration }: any) => ({
  buttonPermissions: global.configure.buttonPermissions,
  list: ListingTransactionDeclaration.list,
  windowConfigs: ListingTransactionDeclaration.windowConfigs,
  configLoading: ListingTransactionDeclaration.configLoading,
}))(Window);
